﻿using Application.DTO.Dictionary;
using Application.DTO;
using Application.IService.Dictionary;
using AutoMapper;
using Domain.Entity.Dictionary;
using Infrastructure.IRepository;
using Infrastructure.IRepository.Dictionary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Application.Service.Dictionary
{
    public class DictionaryKeyService : BaseService<DictionaryKey>, IDictionaryKeyService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IDictionaryKeyRepository dictionaryKeyRepository;
        private readonly IDictionaryValueRepository dictionaryValueRepository;
        private readonly IMapper mapper;
        public DictionaryKeyService(IUnitOfWork unitOfWork, IDictionaryKeyRepository dictionaryKeyRepository, IDictionaryValueRepository dictionaryValueRepository, IMapper mapper) : base(unitOfWork, dictionaryKeyRepository)
        {
            this.unitOfWork = unitOfWork;
            this.dictionaryKeyRepository = dictionaryKeyRepository;
            this.dictionaryValueRepository = dictionaryValueRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加字典集
        /// </summary>
        /// <param name="dto">字典集</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> InsertDictionaryList(DictionaryListFormDTO dto)
        {
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //获取到字典主表信息
                    DictionaryKey dickey = mapper.Map<DictionaryKey>(dto);
                    //添加主表信息
                    await dictionaryKeyRepository.Insert(dickey);

                    //保存主表信息，以获取ID
                    int h = await unitOfWork.SaveChanges();

                    //获取字典从表信息集合
                    List<DictionaryValue> values = new List<DictionaryValue>();
                    dto.Details.ForEach(e =>
                    {
                        DictionaryValue temp = mapper.Map<DictionaryValue>(e);
                        temp.DicKeyId = dickey.Id;
                        values.Add(temp);
                    });
                    //批量添加字典从表信息
                    await dictionaryValueRepository.InsertBatch(values);

                    //保存字典两表信息
                    h += await unitOfWork.SaveChanges();

                    tran.Commit();
                    return new ResultDTO<string>("", Domain.Enum.ResultStatusCode.SUCCESS, "添加字典集成功！！！");
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new ResultDTO<string>(ex.Message, Domain.Enum.ResultStatusCode.HANDLEFAIL, "未知错误！！！");
                }
            }
        }
        /// <summary>
        /// 修改字典集
        /// </summary>
        /// <param name="dto">字典集</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> UpdateDictionaryList(DictionaryListFormDTO dto)
        {
            using (var tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //获取到字典主表信息
                    DictionaryKey dickey = mapper.Map<DictionaryKey>(dto);
                    //修改主表信息
                    await dictionaryKeyRepository.Update(dickey);

                    //获取该表之前的字典从表数据信息
                    List<DictionaryValue> valueLists = (await dictionaryValueRepository.GetAll()).AsNoTracking().Where(m => m.DicKeyId == dto.Id && !m.IsDeleted).ToList();
                    //获取dto中待修改的字典从表数据
                    List<DictionaryValue> details = mapper.Map<List<DictionaryValue>>(dto.Details);

                    //比较修改的字典项在数据库是否存在，取存在的放到修改集合
                    IEnumerable<int> editValuesIds = details.Select(m => m.Id).Intersect(valueLists.Select(m => m.Id));
                    //获取新增到的字典项
                    IEnumerable<int> addValuesIds = details.Select(m => m.Id).Except(valueLists.Select(m => m.Id));
                    //获取删除项
                    IEnumerable<int> removeValuesIds = valueLists.Select(m => m.Id).Except(details.Select(m => m.Id));

                    //将以上三个ID集合转为实体集合
                    List<DictionaryValue> editValues = await dictionaryValueRepository.GetDictionaryValueById(editValuesIds);
                    List<DictionaryValue> addValues = await dictionaryValueRepository.GetDictionaryValueById(addValuesIds);
                    List<DictionaryValue> removeValues = await dictionaryValueRepository.GetDictionaryValueById(removeValuesIds);

                    //批量修改字典从表信息
                    await dictionaryValueRepository.UpdateBatch(editValues);
                    await dictionaryValueRepository.InsertBatch(addValues);
                    await dictionaryValueRepository.DeleteBatch(removeValues);

                    //保存字典两表信息
                    int h = await unitOfWork.SaveChanges();

                    tran.Commit();
                    return new ResultDTO<string>(""+h, Domain.Enum.ResultStatusCode.SUCCESS, "修改字典集成功！！！");
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new ResultDTO<string>(ex.Message, Domain.Enum.ResultStatusCode.HANDLEFAIL, "未知错误！！！");
                }
            }
        }
        /// <summary>
        /// 删除字典集，采用逻辑删除
        /// </summary>
        /// <param name="ids">字典键ID集合</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> SoftDeleteDictionaryList(string ids)
        {
            //分割id
            int[] idArray = Array.ConvertAll(ids.Split(','), int.Parse);

            List<DictionaryKey> list = new List<DictionaryKey>();
            //循环逻辑删除
            foreach (var item in idArray)
            {
                //查询字典主表是否存在
                var m = await (await dictionaryKeyRepository.GetAll()).FirstOrDefaultAsync(m => m.Id == item);
                if (m != null)
                {
                    m.IsDeleted = true;
                    list.Add(m);
                }
            }

            //批量修改字典主表数据
            await dictionaryKeyRepository.UpdateBatch(list);

            //保存
            int h = await unitOfWork.SaveChanges();

            return new ResultDTO<string>($"{h}", Domain.Enum.ResultStatusCode.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 查询字典键集合
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDTO<List<DictionaryKeyShowDTO>>> SearchDictionaryKeys()
        {
            var temp = (await dictionaryKeyRepository.GetAll()).Where(m => !m.IsDeleted).ToList();
            //获取字典主表信息
            List<DictionaryKeyShowDTO> list = mapper.Map<List<DictionaryKeyShowDTO>>(temp);

            return new ResultDTO<List<DictionaryKeyShowDTO>>(list);
        }
    }
}
